﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.IServices.PurchaseOrder;
using System.Linq;
using System.Threading.Tasks;
using System;
using ProTrack.Entity;
using Newtonsoft.Json;
using ProTrack.Utility;
using System.Collections.Generic;
using ProTrack.Report;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 到货通知
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class WareHouseInboundBillController : ControllerBase
    {
        public WareHouseInboundBillController(IWareHouseInboundBillServices services, LogHelper logHelper)
        {
            Services = services;
            LogHelper = logHelper;
        }

        public IWareHouseInboundBillServices Services { get; }
        public LogHelper LogHelper { get; }

        /// <summary>
        /// 获取所有到货通知单
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("到货通知单-获取所有", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 分页获取到货通知单
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="Number">到货通知单编号</param>
        /// <param name="VendorId">供应商名称</param>
        /// <param name="WareHouseId">入货仓</param>
        /// <param name="Status">单据状态：-1：全部，0待审核  1已审核</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string Number, [FromQuery] string VendorId, [FromQuery] string WareHouseId, [FromQuery] int Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                Number = Number ?? "";
                VendorId = VendorId ?? "";
                WareHouseId = WareHouseId ?? "";
                var list = await Services.GetAsync(PageIndex, PageSize, Number, VendorId, WareHouseId, Status);
                status.Data = list;
                status.Count = await Services.GetCountAsync(Number, VendorId, WareHouseId, Status);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("到货通知单-分页获取", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 根据到货通知单Id获取采购数据
        /// </summary>
        /// <param name="WareHouseInboundBillId">单据Id</param>
        /// <returns></returns>
        [HttpGet("GetWareHouseInboundBillIdAsync")]
        public async Task<IActionResult> GetWareHouseInboundBillIdAsync([FromQuery] string WareHouseInboundBillId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetWareHouseInboundBillIdAsync(WareHouseInboundBillId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("到货通知单-获取到货数量", ex, HttpContext);
            }
            return Ok(status);
        }


        /// <summary>
        /// 根据采购单 获取未到货的商品
        /// </summary>
        /// <param name="OrderPoId"></param>
        /// <returns></returns>
        [HttpGet("GetOrderPoByItem")]
        public async Task<IActionResult> GetOrderPoByItem([FromQuery] string OrderPoId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetOrderPoByItem(OrderPoId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("到货通知单-获取到货物料", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 新增到货通知单
        /// </summary>
        /// <param name="model">到货通知单模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] WareHouseInboundBill model, [FromForm] string WareHouseInboundBillItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<WareHouseInboundBillItem> list = new List<WareHouseInboundBillItem>();
            try
            {
                if (!string.IsNullOrEmpty(WareHouseInboundBillItemString))
                {
                    list = JsonConvert.DeserializeObject<List<WareHouseInboundBillItem>>(WareHouseInboundBillItemString);
                    list.ForEach(x =>
                    {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;
                var isSuccess = await Services.AddAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("到货通知单-新增", ex, HttpContext);
            }
            return Ok(status);
        }




        /// <summary>
        /// 到货通知单修改
        /// </summary>
        /// <param name="model">到货通知单模型</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] WareHouseInboundBill model, [FromForm] string WareHouseInboundBillItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<WareHouseInboundBillItem> list = new List<WareHouseInboundBillItem>();
            try
            {
                if (!string.IsNullOrEmpty(WareHouseInboundBillItemString))
                {
                    list = JsonConvert.DeserializeObject<List<WareHouseInboundBillItem>>(WareHouseInboundBillItemString);
                    list.ForEach(x =>
                    {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.UpdateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        x.WareHouseInboundBillId = model.Id;
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;

                var isSuccess = await Services.UpdateAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";

                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("到货通知单-修改", ex, HttpContext);
            }
            return Ok(status);
        }

        /// <summary>
        /// 批量删除到货通知单
        /// </summary>
        /// <param name="Ids">Id数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("到货通知单-批量删除", ex, HttpContext);
            }
            return Ok(status);
        }


        /// <summary>
        /// 修改到货通知订单状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        [HttpPut("UpdateWareHouseInboundBillStatus")]
        public async Task<IActionResult> UpdateWareHouseInboundBillStatus([FromForm] long Id, [FromForm] int Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                // 根据报价单 Id 查询数据库，找到对应的报价单对象
                var isSuccess = await Services.UpdateWareHouseInboundBillStatus(Id, Status);


                if (isSuccess)
                {
                    var msg = Status == 0 ? "反审成功" : "审核成功";
                    status.Code = 0;
                    status.Msg = msg;
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("到货通知订单-修改状态", ex, HttpContext);
            }

            return Ok(status);
        }


        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {

                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[] {
                    new ReportDomain{ Title="序号",Fileld="No"},
                    new ReportDomain{ Title="到货通知单编号",Fileld="Number"},
                    new ReportDomain{ Title="供应商名称",Fileld="VendorName"},
                    new ReportDomain{ Title="入货仓",Fileld="WareHouseName"},
                    new ReportDomain{ Title="交货日期",Fileld="DeliveryDate"},
                    new ReportDomain{ Title="到货时间",Fileld="ReceiveDate"},
                    new ReportDomain{ Title="通知单状态",Fileld="Status"},
                    new ReportDomain{ Title="创建时间",Fileld="CreateTime"},
                    new ReportDomain{ Title="关联订单",Fileld="OrderPoId"},
                };
                var fileArray = BaseReport.Export(list, "到货通知信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "到货通知信息.xls");
            }
            catch (Exception ex)
            {

                //此处应当日志记录
                await LogHelper.WriteErrorLog("到货通知订单-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }

        }




    }
}
